import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Table,
  Tree,
  Input,
  Select,
  Button,
  Icon,
  Pagination,
  Modal,
  Switch,
  message,
  Form,
  Radio,
} from 'antd';
import styles from '../userManage/index.css';
import { Dispatch, AnyAction } from 'redux';
import { produce, Draft } from 'immer';
import { DEFAULT_PAGE_NUM, DEFAULT_PAGE_SIZE } from '@/const';
import { userStatus, deleteDept, addDept, editDept, deptList } from '@/services/systemDevice';
import { DeviceListsItem } from '@/models/connect';
import { FormComponentProps } from 'antd/es/form';
import { isMenuVisible } from './../../../utils/utils';
import _ from 'lodash';
import { async } from 'q';
const { Option } = Select;
const { TextArea } = Input;

interface userPsops extends FormComponentProps {
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
  // deptList?: DeviceListsItem;
  form: FormComponentProps['form'];
}
interface userManage {
  pageTotal: number;
  filterQueryParams: any;
  userStatus: any;
  params: any;
  showModel: boolean;
  sdtDeptId: any;
  title: any;
  isTrue: boolean;
  isAdd: boolean;
  isChecked: boolean;
  addChecked: boolean;
  deptList: any;
}
// @connect(({ loading, systemDevice }: any) => ({
//     loading: loading.effects['systemDevice/userList'],
//     deptList: systemDevice.deptList
// }))
class deptManage extends Component<userPsops, userManage> {
  state: userManage = {
    userStatus: [], //用户状态
    pageTotal: 0,
    filterQueryParams: {
      pageNum: 1,
      pageSize: 10,
      sdtDeptName: '',
      sdtStatus: '',
    },
    params: {
      dictType: 'sys_dept_status',
    },
    showModel: false,
    sdtDeptId: [],
    title: '',
    isTrue: false,
    isAdd: true,
    isChecked: true,
    addChecked: true,
    deptList: {},
  };
  async componentWillMount() {
    const { dispatch } = this.props;
    const [err, data] = await userStatus(this.state.params);
    if (!err) {
      this.setState(
        produce((draft: Draft<userManage>): void => {
          draft.userStatus = data;
        }),
      );
    }
    isMenuVisible('system:dept:list') && this.handleFilterQuery();
  }
  handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 部门名称
    e.persist();
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.filterQueryParams.sdtDeptName = e.target.value;
      }),
    );
  };
  handleChangeStatus = (e: string) => {
    // 部门状态
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.filterQueryParams.sdtStatus = e;
      }),
    );
  };
  // 页码变化
  handlePageChange: (pageNum: number, pageSize: number | undefined) => void = pageNum => {
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.filterQueryParams.pageNum = pageNum;
      }),
      () => isMenuVisible('system:dept:list') && this.handleFilterQuery(),
    );
  };
  handleFilterQuery = async () => {
    // 搜索
    // const { dispatch } = this.props;
    const [err, data] = await deptList(this.state.filterQueryParams);
    if (!err) {
      this.setState(
        produce((draft: Draft<userManage>): void => {
          draft.deptList = data;
        }),
      );
    }
    // console.log(this.state.deptList);
    // dispatch({ type: 'systemDevice/deptList', payload: this.state.filterQueryParams });
  };
  handleSure = async () => {
    // 确认删除
    const [err, data] = await deleteDept({ sdtDeptId: this.state.sdtDeptId });
    if (!err) {
      this.setState(
        produce((draft: Draft<userManage>): void => {
          draft.isTrue = false;
        }),
      );
      message.info('删除成功');
    } else {
      this.setState(
        produce((draft: Draft<userManage>): void => {
          draft.isTrue = false;
        }),
      );
    }
    isMenuVisible('system:dept:list') && this.handleFilterQuery();
  };
  handleSigDelete = (record: any) => {
    // 删除
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.sdtDeptId = record.sdtDeptId;
      }),
    );
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.title = '确定要删除选中数据吗？';
        draft.isTrue = true;
      }),
    );
  };
  handleAddDept = () => {
    //新增
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.showModel = true;
        draft.isAdd = true;
      }),
    );
  };
  handleSubmit = (e: any) => {
    // 确认新增
    // e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log(values);
      values.sdtStatus = values.sdtStatus ? '0' : '1';
      if (!err) {
        this.handleInsert(values);
      }
    });
  };
  //修改
  handleEditor = (record: any) => {
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.isAdd = false;
        draft.isChecked = record.sdtStatus === '0' ? true : false;
        draft.showModel = true;
      }),
    );
    this.props.form.setFieldsValue({
      sdtDeptName: record.sdtDeptName,
      sdtOrderNum: record.sdtOrderNum,
      sdtLeader: record.sdtLeader,
      sdtPhone: record.sdtPhone,
      sdtEmail: record.sdtEmail,
      sdtDeptId: record.sdtDeptId,
      sdtStatus: record.sdtStatus == 0 ? true : false,
    });
  };
  handleInsert = async values => {
    // 确认插入(判断新增和修改)
    if (this.state.isAdd) {
      const [err, data] = await addDept(values);
      if (!err) {
        this.setState(
          produce((draft: Draft<userManage>): void => {
            draft.showModel = false;
          }),
        );
        message.info('新增成功');
        this.props.form.resetFields();
      }
    } else {
      const [err, data] = await editDept(values);
      if (!err) {
        this.setState(
          produce((draft: Draft<userManage>): void => {
            draft.showModel = false;
          }),
        );
        message.info('修改成功');
        this.props.form.resetFields();
      }
    }
    isMenuVisible('system:dept:list') && this.handleFilterQuery();
  };
  onSwitchChange = (checked: any) => {
    // 切换选中状态
    this.setState({ isChecked: checked });
    this.setState({ addChecked: checked });
  };
  columns: any = [
    {
      title: '部门名称',
      dataIndex: 'sdtDeptName',
      key: 'sdtDeptName',
    },
    {
      title: '排序',
      dataIndex: 'sdtOrderNum',
      key: 'sdtOrderNum',
    },
    {
      title: '状态',
      dataIndex: 'sdtStatus',
      key: 'sdtStatus',
      render: (text: any, record: any) => {
        return record.sdtStatus == 0 ? (
          <span style={{ color: 'rgb(69, 235, 167)' }}>正常</span>
        ) : (
          <span style={{ color: '#cb3203' }}>停用</span>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'sdtCreateTime',
      key: 'sdtCreateTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        return (
          <span className={styles.one}>
            {isMenuVisible('system:dept:edit') && (
              <a
                onClick={() => {
                  this.handleEditor(record);
                }}
              >
                编辑
              </a>
            )}
            {isMenuVisible('system:dept:remove') && (
              <a
                onClick={() => {
                  this.handleSigDelete(record);
                }}
              >
                删除
              </a>
            )}
          </span>
        );
      },
    },
  ];
  render() {
    // const { deptList = [] } = this.props;
    const { userStatus } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      wrapperCol: { span: 16 },
    };
    const title = this.state.isAdd ? '新增部门' : '编辑部门';
    return (
      <div className={styles.container}>
        <div className={styles.userRight}>
          <div style={{ overflow: 'hidden' }}>
            <div className={styles['inforAnasy-container-top-btn']}>
              {isMenuVisible('system:dept:add') && (
                <Button type="link" onClick={this.handleAddDept}>
                  <Icon type="plus" />
                  新增
                </Button>
              )}
            </div>
            <div>
              <div className={styles['dev-search-select']}>
                <Input
                  onChange={this.handleChange}
                  value={this.state.filterQueryParams.sdtDeptName}
                  addonBefore="部门名称"
                  type="text"
                />
              </div>
              <div className={styles['dev-search-select']}>
                <span className={styles['dev-search-select-title']}>部门状态</span>
                <Select
                  defaultValue="请选择"
                  style={{ width: 200 }}
                  value={this.state.filterQueryParams.sdtStatus}
                  onChange={this.handleChangeStatus}
                >
                  {_.map(userStatus, (item: any, index: number) => (
                    <Option key={index} value={item.dictValue}>
                      {item.dictLabel}
                    </Option>
                  ))}
                </Select>
              </div>
              {isMenuVisible('system:dept:list') && (
                <Button
                  type="link"
                  className={styles['search']}
                  onClick={() => {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.filterQueryParams.pageNum = 1;
                      }),
                      () => {
                        this.handleFilterQuery();
                      },
                    );
                  }}
                >
                  搜索
                </Button>
              )}
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.sdtDeptName = '';
                      draft.filterQueryParams.sdtStatus = undefined;
                    }),
                  );
                }}
              >
                重置
              </Button>
            </div>
          </div>
          <Table
            scroll={{ y: '500px' }}
            pagination={false}
            columns={this.columns}
            dataSource={this.state.deptList.rows}
            rowKey="sdtDeptName"
          />
          <div className="pagination-box">
            <Pagination
              defaultCurrent={this.state.filterQueryParams.pageNum}
              current={this.state.filterQueryParams.pageNum}
              onChange={this.handlePageChange}
              total={this.state.deptList.total ? this.state.deptList.total : 0}
            />
            <span className="pagination-title-box">
              第{this.state.filterQueryParams.pageNum}/
              {Math.ceil(
                (this.state.deptList.total ? this.state.deptList.total : 0) /
                  this.state.filterQueryParams.pageSize,
              )}
              页 共{this.state.deptList.total ? this.state.deptList.total : 0}条
            </span>
          </div>
          <Modal
            title={title}
            visible={this.state.showModel}
            className="userModal_box deptModal_box"
            onCancel={() => {
              this.props.form.resetFields();
              this.setState({ showModel: false, addChecked: true });
            }}
          >
            <Form className="ant-advanced-search-form">
              <Form.Item {...formItemLayout} label="部门Id" style={{ display: 'none' }}>
                {getFieldDecorator('sdtDeptId', {
                  rules: [{ required: false, message: '部门Id' }],
                })(<Input type="text" placeholder="请输入部门Id" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="上级部门名称" style={{ display: 'none' }}>
                {getFieldDecorator('sdtDeptPid', {
                  initialValue: 0,
                  rules: [{ required: true, message: '请输入部门名称' }],
                })(<Input type="text" placeholder="请输入部门名称" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="部门名称">
                {getFieldDecorator('sdtDeptName', {
                  rules: [
                    { required: true, message: '请输入部门名称' },
                    {
                      max: 20,
                      message: '最多输入20位中文名',
                    },
                  ],
                })(<Input type="text" placeholder="请输入部门名称" maxLength={20} />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="显示排序">
                {getFieldDecorator('sdtOrderNum', {
                  rules: [
                    {
                      required: false,
                      pattern: new RegExp(/^[0-9]\d*$/, 'g'),
                      message: '请输入数字!',
                    },
                    {
                      max: 4,
                      message: '排序不能大于4位数',
                    },
                  ],
                })(<Input placeholder="请输入序号" maxLength={10} />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="负责人">
                {getFieldDecorator('sdtLeader', {
                  rules: [
                    { required: false },
                    {
                      max: 20,
                      message: '最多输入20位中文名',
                    },
                  ],
                })(<Input placeholder="请输入负责人" maxLength={20} />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="联系电话">
                {getFieldDecorator('sdtPhone', {
                  rules: [
                    {
                      required: true,
                      pattern: /^18[0-9]\d{8}$/,
                      message: '请输入正确的电话号码',
                    },
                  ],
                })(<Input placeholder="请输入联系电话" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="邮箱">
                {getFieldDecorator('sdtEmail', {
                  rules: [
                    {
                      required: true,
                      pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
                      message: '邮箱输入不正确',
                    },
                  ],
                })(<Input placeholder="请输入邮箱" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="部门状态">
                {getFieldDecorator('sdtStatus', {
                  initialValue: true,
                  rules: [{ required: false }],
                })(
                  <Switch
                    defaultChecked={true}
                    checked={this.state.isAdd ? this.state.addChecked : this.state.isChecked}
                    onChange={this.onSwitchChange}
                  />,
                )}
              </Form.Item>
            </Form>
            <div className={styles.footBtnArea}>
              <div
                style={{ marginRight: '30px' }}
                className={styles.foot_btn}
                onClick={this.handleSubmit}
              >
                确定
              </div>
              <div
                className={styles.foot_btn}
                onClick={() => {
                  this.setState({ showModel: false, addChecked: true });
                  this.props.form.resetFields();
                }}
              >
                取消
              </div>
            </div>
          </Modal>
          <Modal
            title="系统提示"
            className={styles.modal}
            visible={this.state.isTrue}
            onCancel={() => {
              this.setState({ isTrue: false });
            }}
          >
            <div className={styles.titles}>{this.state.title}</div>
            <div className={styles.footBtn}>
              <div
                style={{ marginRight: '30px' }}
                className={styles.foot_btn}
                onClick={this.handleSure}
              >
                确定
              </div>
              <div
                className={styles.foot_btn}
                onClick={() => {
                  this.setState({ isTrue: false });
                }}
              >
                取消
              </div>
            </div>
          </Modal>
        </div>
      </div>
    );
  }
}
export default Form.create<userPsops>()(deptManage);
